package com.sapuo.enroll.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by tao.
 * Date: 2021/6/28 16:37
 * 描述:
 */
public class CDKeyEncryptUtils {
    //--------------AES---------------
    private static final String KEY = "53214681";  // 密匙，必须16位
    private static final String OFFSET = "85413275"; // 偏移量
    private static final String ENCODING = "UTF-8"; // 编码
    private static final String ALGORITHM = "DES"; //算法
    private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding"; // 默认的加密算法，CBC模式

    public static String AESencrypt(String data) throws Exception {
        //指定算法、获取Cipher对象(DES/CBC/PKCS5Padding：算法为，工作模式，填充模式)
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        //根据自定义的加密密匙和算法模式初始化密钥规范
        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
        //CBC模式偏移量IV
        IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
        //初始化加密模式
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        //单部分加密结束，重置Cipher
        byte[] encrypted = cipher.doFinal(data.getBytes(ENCODING));
        //加密后再使用BASE64做转码
        return new Base64().encodeToString(encrypted);
    }

    /**
     * AES解密
     *
     * @param data
     * @return String
     * @author tao
     * @date 2021-6-15 16:46:07
     */
    public static String AESdecrypt(String data) throws Exception {
        //指定算法、获取Cipher对象(DES/CBC/PKCS5Padding：算法为，工作模式，填充模式)
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        //根据自定义的加密密匙和算法模式初始化密钥规范
        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
        //CBC模式偏移量IV
        IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
        //初始化解密模式
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        //先用base64解码
        byte[] buffer = new Base64().decode(data);
        //单部分加密结束，重置Cipher
        byte[] encrypted = cipher.doFinal(buffer);
        return new String(encrypted, ENCODING);
    }

    public static void main(String[] args) throws Exception {
//        for (int i = 0; i < 10; i++) {
//            String CDKey = CDKeyUtil.createCDkey("67", "0", "1");
//            System.out.println("激活码：" + CDKey);
//            String deCDkey = CDKeyUtil.deCDkey(CDKey, "1");
//            System.out.println("激活码解密：" + deCDkey);
//        }
        String CDKey = CDKeyUtil.createCDkey("67", "3", "1");
        System.out.println(CDKey);

        String deCDkey = CDKeyUtil.deCDkey(CDKey,"1");

        System.out.println(deCDkey);
    }
}